package xml;

import java.util.ArrayList;

/**
 * Instances of this class each represent an XML tag.
 *
 * @see XML
 * @author Neil Dickson
 */
public class Tag implements Element {
	private	String					name;
	private ArrayList<String>		attributeNames;
	private ArrayList<String>		attributeValues;
	private ArrayList<Element>		children;
	private	boolean					isSelfClosing;

	public static final int INITIAL_NUM_ATTRIBUTES = 4;
	public static final int INITIAL_NUM_CHILDREN = 4;

	public Tag(String name) {
		this.name = name;
		attributeNames = null;
		attributeValues = null;
		children = null;
		isSelfClosing = true;
	}

	public String getName() {
		return name;
	}

	public boolean hasChildren() {
		return children!=null && children.size()!=0;
	}

	public ArrayList<Element> getChildren() {
		return children;
	}

	public void addAttribute(String key,String value) {
		if (attributeNames==null) {
			attributeNames = new ArrayList<String>(INITIAL_NUM_ATTRIBUTES);
			attributeValues = new ArrayList<String>(INITIAL_NUM_ATTRIBUTES);
		}
		attributeNames.add(key);
		attributeValues.add(value);
	}

	public String getAttribute(String key) {
		if (attributeNames!=null) {
			for (int i=0;i<attributeNames.size();++i) {
				if (attributeNames.get(i).equals(key)) {
					return attributeValues.get(i);
				}
			}
		}
		return null;
	}

	public boolean hasAttribute(String key) {
		if (attributeNames!=null) {
			for (int i=0;i<attributeNames.size();++i) {
				if (attributeNames.get(i).equals(key)) {
					return true;
				}
			}
		}
		return false;
	}

	public void addChild(Element child) {
		if (children==null) {
			children = new ArrayList<Element>(INITIAL_NUM_CHILDREN);
		}
		children.add(child);
		isSelfClosing = false;
	}

	public boolean isSelfClosing() {
		return isSelfClosing;
	}

	public void setSelfClosing(boolean selfClosing) {
		isSelfClosing = selfClosing;
	}

	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append("<").append(name);
		if (attributeNames!=null) {
			for (int i=0;i<attributeNames.size();++i) {
				buf.append(" ").append(attributeNames.get(i)).append("=\"").append(XML.escape(attributeValues.get(i))).append("\"");
			}
		}
		if (isSelfClosing && (children==null || children.size()==0)) {
			buf.append("/>");
		}
		else {
			buf.append(">");
			for (Element element : children) {
				buf.append(element);
			}
			buf.append("</").append(name).append(">");
		}
		return buf.toString();
	}
}